import SwiftUI
import Combine

class AppVersionChecker: ObservableObject {
    @Published var updateAvailable = false
    @Published var appInfo: AppInfo?
    @Published var error: Error?
    @Published var isLoading = false
  
    func checkForUpdates(bundleId: String = Bundle.main.bundleIdentifier ?? "") {
        guard let url = URL(string: "https://itunes.apple.com/lookup?bundleId=\(bundleId)") else {
            error = NSError(domain: "Invalid URL", code: -1, userInfo: nil)
            return
        }
        
        isLoading = true
        URLSession.shared.dataTaskPublisher(for: url)
            .map(\.data)
            .decode(type: AppStoreResponse.self, decoder: JSONDecoder())
            .receive(on: DispatchQueue.main)
            .sink(
                receiveCompletion: { [weak self] completion in
                    self?.isLoading = false
                    if case let .failure(error) = completion {
                        self?.error = error
                    }
                },
                receiveValue: { [weak self] response in
                    guard let self = self,
                          let appInfo = response.results.first else {
                        self?.error = NSError(domain: "No app info received", code: -2, userInfo: nil)
                        return
                    }
                    
                    self.appInfo = appInfo
                    self.updateAvailable = self.isNewVersion(current: self.getCurrentVersion(), new: appInfo.version)
                    print("updateAvailable \(updateAvailable) version: \(self.getCurrentVersion()) appversion: \(appInfo.version)")
                }
            )
            .store(in: &subscriptions)
    }
    
    private func isNewVersion(current: String, new: String) -> Bool {
        // 分割版本号并转换为整数数组
        let currentComponents = current.components(separatedBy: ".").compactMap { Int($0) }
        let newComponents = new.components(separatedBy: ".").compactMap { Int($0) }
        
        // 获取最大组件数，确保所有组件都被比较
        let maxCount = max(currentComponents.count, newComponents.count)
        
        for i in 0..<maxCount {
            // 不足的组件补0（例如 1.2 视为 1.2.0）
            let currentComponent = i < currentComponents.count ? currentComponents[i] : 0
            let newComponent = i < newComponents.count ? newComponents[i] : 0
            
            if newComponent > currentComponent {
                return true
            } else if newComponent < currentComponent {
                return false
            }
        }
        
        // 所有组件都相等，不是新版本
        return false
    }
    
    private func getCurrentVersion() -> String {
        return Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "0.0.0"
    }
    
    private var subscriptions = Set<AnyCancellable>()
}

// 添加缺失的数据模型
struct AppStoreResponse: Decodable {
    let results: [AppInfo]
}

struct AppInfo: Identifiable, Decodable {
    let id = UUID()
    let version: String
    let releaseNotes: String?
    let trackViewUrl: String
}
